//
//  HXIflyAddressBookTableViewController.m
//  KD
//
//  Created by ifly on 16/7/20.
//  Copyright © 2016年 Whx. All rights reserved.
//

#import "HXIflyAddressBookTableViewController.h"
#import "PinYinForObjc.h"
#import "HXGetGroupMembersModel.h"

@interface HXIflyAddressBookTableViewController ()<UISearchControllerDelegate,UISearchBarDelegate>

@property (nonatomic,strong)UISearchController * searchCon;
@property (nonatomic,strong) NSMutableDictionary * dataDic;
@property (nonatomic,strong) NSArray * allkeys;

@end

@implementation HXIflyAddressBookTableViewController



- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self createTableViewHeardView];
}

/**
 搜索控制器
 */
-(void)createTableViewHeardView {
    
    self.tableView.tableFooterView = [[UIView alloc]init];
    [self.tableView registerNib:[UINib nibWithNibName:@"HXAddressBookTableViewCell" bundle:nil] forCellReuseIdentifier:@"HXAddressBookTableViewCell"];
    self.tableView.rowHeight = UITableViewAutomaticDimension;
    self.tableView.estimatedRowHeight = 54;
    _searchCon = [[UISearchController alloc] initWithSearchResultsController:nil];
    _searchCon.searchBar.delegate = self;
    [_searchCon.searchBar sizeToFit];
    _searchCon.dimsBackgroundDuringPresentation = NO;
    _searchCon.hidesNavigationBarDuringPresentation = NO;
    self.tableView.tableHeaderView = _searchCon.searchBar;
    self.tableView.mj_header=[AWRefreshHeader headerWithRefreshingTarget:self refreshingAction:@selector(loadData)];
    self.tableView.mj_footer.automaticallyChangeAlpha = YES;
    self.tableView.mj_footer.automaticallyHidden = NO;
    
    self.tableView.sectionIndexColor = [UIColor blueColor];
//    self.tableView.sectionIndexBackgroundColor = [UIColor grayColor];
    
    [self.tableView.mj_header beginRefreshing];
}

-(void)searchBarSearchButtonClicked:(UISearchBar *)searchBar {
    
    if (searchBar.text.length > 0) {
        
        [self loadDataWithQuery:searchBar.text];
    }
}
- (void)searchBarCancelButtonClicked:(UISearchBar *)searchBar{

    [self loadDataWithQuery:@""];
}

-(void)loadData{

    [self loadDataWithQuery:@""];
}

//获取拼音首字母(传入汉字字符串, 返回大写拼音首字母)
- (NSString *)firstCharactor:(NSString *)aString
{
    //转成了可变字符串
    NSMutableString *str = [NSMutableString stringWithString:aString];
    //先转换为带声调的拼音
    CFStringTransform((CFMutableStringRef)str,NULL, kCFStringTransformMandarinLatin,NO);
    //再转换为不带声调的拼音
    CFStringTransform((CFMutableStringRef)str,NULL, kCFStringTransformStripDiacritics,NO);
    //转化为大写拼音
    NSString *pinYin = [str capitalizedString];
    //获取并返回首字母
    return [pinYin substringToIndex:1];
}

/**
 加载数据
 */
-(void)loadDataWithQuery:(NSString *)query{

    _dataDic = [NSMutableDictionary dictionary];
    
    [SVProgressHUD showWithStatus:@"正在加载..."];
    
    [NetworkAPI getPhoneBookWithQuery:query Success:^(HXGetGroupMembersModel *result) {
        
        if ([result.code isEqualToString:@"200"]) {
            
            for (HXGetGroupMembersListModel * listModel in result.result) {
                
                //数据源字典中的key值
                NSString *charindex = [[PinYinForObjc chineseConvertToPinYin:listModel.PersonName] substringToIndex:1];
                
                //key值对应的数组
                NSMutableArray *arr = [_dataDic objectForKey:charindex];
              
                if(!arr){
                    
                    //如果key值没有对应的数组 则重新创建新的数组去接收
                    NSMutableArray *newsArr = [[NSMutableArray alloc]init];
                    
                    [newsArr addObject:listModel];
                    
                    [_dataDic setObject:newsArr forKey:charindex];
                    
                }else if (arr){
                    
                    [arr addObject:listModel];
                }
            }
           
            _allkeys = [[_dataDic allKeys] sortedArrayUsingSelector:@selector(compare:)];
            
            [self.tableView reloadData];
            [SVProgressHUD dismiss];
            [self.tableView.mj_header endRefreshing];
        }else if ([result.code isEqualToString:@"400"]){
        
            [SVProgressHUD showSuccessWithStatus:@"暂无数据!"];
        }else{
        
            [SVProgressHUD showErrorWithStatus:@"暂无数据!"];
        }
        
    } failure:^(NSError *err) {
        
        [SVProgressHUD showErrorWithStatus:@"网络错误!"];

    }];
    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {

    return _allkeys.count;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {

    NSArray * array = [_dataDic objectForKey:_allkeys[section]];
    
    return array.count;
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"HXAddressBookTableViewCell" forIndexPath:indexPath];
    
    if (cell == nil) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"HXAddressBookTableViewCell"];
    }
    
    NSArray * array = [_dataDic objectForKey:_allkeys[indexPath.section]];
    
    HXGetGroupMembersListModel * model = array[indexPath.row];
    
    cell.textLabel.text = model.PersonName;
    
    return cell;
}

/**
 单元格的点击方法
 */
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{

    NSArray * array = [_dataDic objectForKey:_allkeys[indexPath.section]];
    HXGetGroupMembersListModel * model = array[indexPath.row];
    
    [LTAlertView showTitle:model.PhoneNum message:nil ButtonTitles:@[@"取消",@"呼叫"] OnTapBlock:^(LTAlertView *alert, NSInteger num) {
       
        if(num == 1){
        
          [[UIApplication sharedApplication] openURL:[NSURL URLWithString:[NSString stringWithFormat:@"tel://%@",model.PhoneNum]]];
        }
    }];
}


-(NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
    
    return _allkeys[section];
}


- (nullable NSArray<NSString *> *)sectionIndexTitlesForTableView:(UITableView *)tableView {
    
    NSMutableArray * titleArray = [NSMutableArray arrayWithArray:_allkeys];
    
    [titleArray addObject:@"#"];

    return titleArray;
}

-(NSInteger)tableView:(UITableView *)tableView sectionForSectionIndexTitle:(NSString *)title atIndex:(NSInteger)index {
    
    if (index == 0) {
        [tableView scrollRectToVisible:_searchCon.searchBar.frame animated:YES];
        return -1;
    }
    else {
        return index -1;
    }
}



/*
// Override to support conditional editing of the table view.
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
    // Return NO if you do not want the specified item to be editable.
    return YES;
}
*/

/*
// Override to support editing the table view.
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        // Delete the row from the data source
        [tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade];
    } else if (editingStyle == UITableViewCellEditingStyleInsert) {
        // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
    }   
}
*/

/*
// Override to support rearranging the table view.
- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath {
}
*/

/*
// Override to support conditional rearranging of the table view.
- (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath {
    // Return NO if you do not want the item to be re-orderable.
    return YES;
}
*/

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
